//数据修正
import * as React from 'react';
import {
  Modal,
  Row,
  Col,
  Input,
  Table,
  Button,
  Form,
  Select,
  Upload,
  Icon,
  message,
  Tabs,
  Spin
} from 'antd';

import router from 'umi/router';
import Link from 'umi/link';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FormItem from 'antd/lib/form/FormItem';

const TabPane = Tabs.TabPane;
const Option = Select.Option;

@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class DataCorrection extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      tranUnits: '',
      tranType: '',
      current: {
        lp: 1,
        ld: 1,
        house: 1
      },
      totalSize: {
        lp: 0,
        ld: 0,
        house: 0
      },
      modalVisible: false,
      lpTableData: [],
      ldTableData: [],
      houseTableData: [],
      projectCode: this.props.location.state !== undefined ? this.props.location.state.projectCode : '',
      loading: true,
      buildingData: {
        communityId: '',
        communityName: '',
        buildingId: '',
        buildingName: '',
        buildingCode: '',
        projectCode: '',
        x: '',
        y: ''
      },
      houseData: {
        houseName: '',
        houseCode: '',
        projectCode: '',
        x: '',
        y: ''
      }
    };
  }
  getProject(item, index, type) {
    let buildingData = this.state.buildingData;
    let houseData = this.state.houseData;
    buildingData.communityId = '';
    buildingData.communityName = '';
    buildingData.buildingCode = '';
    buildingData.projectCode = this.state.projectCode;
    houseData.houseCode = '';
    houseData.projectCode = '';
    switch (type) {
      case 'building':
        if (buildingData.buildingName === '') {
          message.warn('请选择需要挂接的楼栋！');
          return false;
        };
        buildingData.communityId = item.communityId;
        buildingData.communityName = item.communityName;
        buildingData.buildingCode = item.buildingCode;
        buildingData.projectCode = this.state.projectCode;
        this.setState({
          buildingData
        });

        axios.get(Api.mountBuilding, {
          params: {
            ...buildingData
          }
        }).then((res) => {
          switch (Number(res.data.msg)) {
            case 0:
              message.error(`挂接失败！`);
              break;
            case 1:
              message.success(`挂接成功！`);
              break;
            case 2:
              message.warn(`请勿重复挂接！`);
              break;
          };
        }).catch((err) => {
          message.error(`挂接失败！`);
        });
        break;
      case 'house':
        if (houseData.houseName === '') {
          message.warn('请选择需要挂接的户！');
          return false;
        };
        houseData.houseCode = item.houseCode;
        houseData.projectCode = this.state.projectCode;
        this.setState({
          houseData
        });
        axios.get(Api.mountHouse, {
          params: {
            ...houseData
          }
        }).then((res) => {
          switch (Number(res.data.msg)) {
            case 0:
              message.error(`挂接失败！`);
              break;
            case 1:
              message.success(`挂接成功！`);
              break;
            case 2:
              message.warn(`请勿重复挂接！`);
              break;
          };
        }).catch((err) => {
          message.error(`挂接失败！`);
        });
        break;
    };


  };
  componentWillMount() {
    this.getLpData(1);
    this.getBuildingData(1);
    this.getHouseData(1);
  }
  query() {
    this.getLpData(this.state.current.lp);
    this.getBuildingData(this.state.current.ld);
    this.getHouseData(this.state.current.house);
  }
  getLpData(page) {
    const that = this;
    let lpTableData = [];
    let totalSize = this.state.totalSize;
    this.toggleLoading(true);
    axios.get(Api.queryCommunity, {
      params: {
        offset: page,
        projectCode: this.state.projectCode
      }
    }).then((res) => {
      totalSize.lp = res.data.count;
      res.data.list.forEach((item, i) => {
        res.data.list[i].key = i;
      });
      that.setState({
        lpTableData: res.data.list,
        totalSize
      });
      this.toggleLoading(false);
    }).catch((err) => {
      this.toggleLoading(false);
    });
  }

  getBuildingData(page) {
    const that = this;
    let lpTableData = [];
    let totalSize = this.state.totalSize;
    this.toggleLoading(true);
    axios.get(Api.queryBuilding, {
      params: {
        offset: page,
        projectCode: this.state.projectCode
      }
    }).then((res) => {
      totalSize.ld = res.data.count;
      res.data.list.forEach((item, i) => {
        res.data.list[i].key = i;
      });
      that.setState({
        ldTableData: res.data.list,
        totalSize
      });
      this.toggleLoading(false);
    }).catch((err) => {
      this.toggleLoading(false);
    });
  }

  getHouseData(page) {
    const that = this;
    let lpTableData = [];
    let totalSize = this.state.totalSize;
    this.toggleLoading(true);
    axios.get(Api.queryHouse, {
      params: {
        offset: page,
        projectCode: this.state.projectCode
      }
    }).then((res) => {
      totalSize.house = res.data.count;
      res.data.list.forEach((item, i) => {
        res.data.list[i].key = i;
      });
      that.setState({
        houseTableData: res.data.list,
        totalSize
      });
      this.toggleLoading(false);
    }).catch((err) => {
      this.toggleLoading(false);
    });
  }

  pageChange(type, page) {
    let current = this.state.current;
    switch (type) {
      case 'lp':
        current.lp = page;
        this.getLpData(page);
        break;
      case 'ld':
        current.ld = page;
        this.getBuildingData(page);
        break;
      default:
        current.house = page;
        this.getHouseData(page);
        break;
    };
    this.setState({
      current
    });
  }
  toggleLoading(loading) {
    this.setState({
      loading
    });
  }
  changeBuilding(item, txt, index) {
    let buildingData = this.state.buildingData;
    buildingData.x = item[index.key].x;
    buildingData.y = item[index.key].y;
    buildingData.buildingId = item[index.key].buildingId;
    buildingData.buildingName = item[index.key].buildingName;
    this.setState({
      buildingData
    });
  }

  changeHouse(item, txt, index) {
    let houseData = this.state.houseData;
    houseData.x = item[index.key].x;
    houseData.y = item[index.key].y;
    houseData.houseName = item[index.key].houseName;
    this.setState({
      houseData
    });
  }

  changeName(e) {
    e.persist();
    this.setState({ projectCode: e.target.value });
  };

  render() {
    let that = this;

    const {
      currentUserLoading,
    } = this.props;
    //表格表头
    const columns = [
      {
        title: '挂接楼盘',
        dataIndex: 'communityName',
        key: 'communityName',
      },
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName',
      },
      {
        title: '挂接状态',
        dataIndex: 'matchStatus',
        key: 'matchStatus',
        render: (text) => (Number(text) === 1 ? <span>成功</span> : <span>失败</span>)
      },
      {
        title: '划转单位',
        dataIndex: 'transferUnit',
        key: 'transferUnit',
      },
      {
        title: '接收日期',
        dataIndex: 'receivedDate',
        key: 'receivedDate',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <Link target="_blank" to={{
            pathname: '/fe/assetManagement/mountMap',
            search: `?data=${JSON.stringify(item)}`,
            state: {
              data: item
            }
          }}>
            <Button type='primary'>
              {Number(item.matchStatus) === 1 ? '修改' : '挂接'}
            </Button>
          </Link>

        ),
      },
    ];

    const ldColumns = [
      {
        title: '挂接楼盘',
        dataIndex: 'communityName',
        key: 'communityName',
      },
      {
        title: '楼宇名称',
        dataIndex: 'buildingName2',
        key: 'buildingName2',
      },
      {
        title: '楼宇编号',
        dataIndex: 'buildingCode',
        key: 'buildingCode',
      },
      {
        title: '租赁状态',
        dataIndex: 'isRent',
        key: 'isRent',
      },
      {
        title: '接管日期',
        dataIndex: 'receivedDate',
        key: 'receivedDate',
      },
      {
        title: '建筑结构',
        dataIndex: 'buildingStructure',
        key: 'buildingStructure',
      },
      {
        title: '总层数',
        dataIndex: 'totalFloor',
        key: 'totalFloor',
      },
      {
        title: '房间数',
        dataIndex: 'houseCount',
        key: 'houseCount',
      },
      {
        title: '挂接楼栋',
        dataIndex: 'list',
        key: 'list',
        render: (items, data, index) => {
          return (
            <Select
              key={index}
              showSearch
              placeholder="请选择挂接楼栋"
              optionFilterProp="children"
              onChange={this.changeBuilding.bind(this, items)}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              defaultValue={data.buildingName}
            >
              {items.map((item, index) => {
                return (<Option name={item.buildingName} key={index} value={item.buildingName}>{item.buildingName}</Option>);
              })}
            </Select>
          );

        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <Button type='primary' onClick={this.getProject.bind(this, item, index, 'building')}>
            挂接
          </Button>
        ),
      },
    ];

    const houseColumns = [
      {
        title: '房屋名称',
        dataIndex: 'houseName2',
        key: 'house_name2',
      },
      {
        title: '房屋编号',
        dataIndex: 'houseCode',
        key: 'houseCode',
      },
      {
        title: '建筑面积',
        dataIndex: 'buildingArea',
        key: 'buildingArea',
      },
      {
        title: '租赁状态',
        dataIndex: 'isRent',
        key: 'isRent',
      },
      {
        title: '用途',
        dataIndex: 'use',
        key: 'use',
      },
      {
        title: '管理方式',
        dataIndex: 'manageType',
        key: 'manageType',
      },
      {
        title: '接管日期',
        dataIndex: 'receivedDate',
        key: 'receivedDate',
      },
      {
        title: '权属状态',
        dataIndex: 'ownershipStatus',
        key: 'ownershipStatus',
      },
      {
        title: '单元',
        dataIndex: 'unitNumber',
        key: 'unitNumber',
      }, {
        title: '挂接房屋',
        dataIndex: 'list',
        key: 'list',
        render: (item, data, index) => {
          return (
            <Select
              key={index}
              showSearch
              placeholder='请选择挂接房屋'
              optionFilterProp="children"
              onChange={this.changeHouse.bind(this, item)}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              defaultValue={data.houseName}
            >
              {item.map((item, index) => {
                return (<Option key={index} value={item.houseName} name={item.houseName}>{item.houseName}</Option>);
              })}
            </Select>
          );

        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <Button type='primary' onClick={this.getProject.bind(this, item, index, 'house')}>
            挂接
          </Button>
        ),
      },
    ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          {
            function () {
              if (this.props.location.state !== undefined) {
                switch (this.props.location.state.type) {
                  case 'upload':
                    return (
                      <div className='contentHeader'>
                        <div className="contentHeaderTitle">
                          <p>上传结果</p>
                          <p>UPLOAD RESULT</p>
                        </div>
                      </div>
                    );
                    break;
                  case 'projectManagement':
                    return (
                      <div className='contentHeader'>
                        <div className="contentHeaderTitle">
                          <p>挂接楼盘</p>
                          <p>HANGING PROPERTY</p>
                        </div>
                      </div>
                    );
                    break;
                }
              } else {
                return (
                  <div>
                    <div className='contentHeader'>
                      <div className="contentHeaderTitle">
                        <p>数据修正</p>
                        <p>DATA CORRECTION</p>
                      </div>

                      <Row>
                        <Form layout="inline" align='center'>
                          <FormItem label='项目编号：' style={{
                            position: 'relative',
                            left: '-36px'
                          }}>
                            <Input
                              onChange={this.changeName.bind(this)}
                              placeholder="请输入项目编号"
                            />
                          </FormItem>
                          <Row style={{
                            textAlign: 'center'
                          }}>
                            <FormItem>
                              <Button type="primary" className="evfilterbtn" onClick={this.query.bind(this)}>
                                查询
              </Button>
                            </FormItem>
                          </Row>
                        </Form>
                      </Row>
                    </div>

                  </div>
                );
              }
            }.bind(this)()
          }

          <Spin spinning={this.state.loading}>
            <Row className="evtablebox">
              <Tabs defaultActiveKey="1">
                <TabPane tab="楼盘情况" key="1">
                  <Table
                    bordered={true}
                    scroll={{ x: true }}
                    align={'center'}
                    columns={columns}
                    dataSource={this.state.lpTableData}
                    pagination={{
                      current: this.state.current.lp,
                      onChange: this.pageChange.bind(this, 'lp'),
                      total: this.state.totalSize.lp,
                      showTotal: total => `共 ${total} 项`
                    }}
                  />
                </TabPane>
                <TabPane tab="楼栋状况" key="2">
                  <Table
                    bordered={true}
                    scroll={{ x: true }}
                    align={'center'}
                    columns={ldColumns}
                    dataSource={this.state.ldTableData}
                    pagination={{
                      current: this.state.current.ld,
                      onChange: this.pageChange.bind(this, 'ld'),
                      total: this.state.totalSize.ld,
                      showTotal: total => `共 ${total} 项`
                    }}
                  />
                </TabPane>
                <TabPane tab="户详情" key="3">
                  <Table
                    bordered={true}
                    scroll={{ x: true }}
                    align={'center'}
                    columns={houseColumns}
                    dataSource={this.state.houseTableData}
                    pagination={{
                      current: this.state.current.house,
                      onChange: this.pageChange.bind(this, 'house'),
                      total: this.state.totalSize.house,
                      showTotal: total => `共 ${total} 项`
                    }}
                  />
                </TabPane>
              </Tabs>
            </Row>
          </Spin>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default DataCorrection;
